// scoreExchange.js
let app = getApp();

Page({
  data: {
    url: '',           // 接口地址
    user: null,        // 当前用户
    goods: []          // 商品列表（从后端获取）
  },

  // ========== 生命周期函数 ==========
  onLoad() {
    this.setData({
      url: app.globalData.url
    });
    // 获取数据
    this.loadUserData();
    this.loadGoods();
  },

  onShow() {
    // 每次页面显示都刷新用户和商品状态
    this.loadUserData();
  },

  // ========== 数据加载 ==========
  loadUserData() {
    const user = wx.getStorageSync('user');
    if (user) {
      this.setData({ user });
      // 更新商品是否可兑换
      this.updateGoodsStatus(user.points);
    }
  },

  loadGoods() {
    wx.request({
      url: this.data.url + 'goods',
      success: (res) => {
        if (res.data.code === 200) {
          const goods = res.data.data.map(g => ({
            id: g.id,
            name: g.name,
            desc: g.description,
            points: g.points,
            image: g.imageUrl,
            isDisabled: false // 初始值，后面根据用户积分更新
          }));
          this.setData({ goods });
          // 再次更新状态（防止 goods 比 user 晚加载）
          const user = this.data.user;
          if (user) this.updateGoodsStatus(user.points);
        } else {
          wx.showToast({ title: '加载商品失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 更新每个商品的“是否可兑换”状态
  updateGoodsStatus(points) {
    const updatedGoods = this.data.goods.map(good => ({
      ...good,
      isDisabled: good.points > points
    }));
    this.setData({ goods: updatedGoods });
  },

  // ========== 兑换核心逻辑 ==========
  onExchange(e) {
    const id = e.currentTarget.dataset.id;
    const good = this.data.goods.find(g => g.id === id);
    const user = this.data.user;

    // 检查登录
    if (!user || !user.id) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    // 检查积分
    if (good.points > user.points) {
      wx.showToast({ title: '积分不足', icon: 'none' });
      return;
    }

    // 弹出确认
    wx.showModal({
      title: '确认兑换',
      content: `确定使用 ${good.points} 积分兑换【${good.name}】吗？`,
      success: (res) => {
        if (res.confirm) {
          // 调用后端兑换接口
          wx.request({
            url: this.data.url + 'exchange',
            method: 'POST',
            header: { 'Content-Type': 'application/json' },
            data: {
              userId: user.id,
              goodsId: good.id
            },
            success: (res) => {
              if (res.data.code === 200) {
                // ✅ 兑换成功：更新本地用户积分
                const newPoints = res.data.data.newPoints;
                const newUser = { ...user, points: newPoints };
                
                // 保存到缓存
                wx.setStorageSync('user', newUser);
                this.setData({ user: newUser });

                // 更新商品状态
                this.updateGoodsStatus(newPoints);

                // 提示成功
                wx.showToast({
                  title: '兑换成功',
                  icon: 'success'
                });

              } else {
                wx.showToast({
                  title: res.data.msg || '兑换失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({ title: '网络错误', icon: 'none' });
            }
          });
        }
      }
    });
  }
});